import 'package:flutter/services.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:permission_handler/permission_handler.dart';

class AppUtils {
  // 权限检测
  static Future<void> checkPermission() async {
    PermissionStatus storageStatus = await Permission.storage.status;
    if (storageStatus != PermissionStatus.granted) {
      storageStatus = await Permission.storage.request();
      if (storageStatus != PermissionStatus.granted) {
        throw "无法储存图片， 请授权";
      }
    }
  }

  // 保存图片
  static Future<bool> saveImage(String? imageUrl, bool isAsset) async {
    try {
      if (imageUrl == null || imageUrl == "") {
        throw "保存失败，图片不存在";
      }
      checkPermission();
      // 保存的图片数据
      Uint8List imageBytes;

      if (isAsset) {
        ByteData bytes = await rootBundle.load(imageUrl);
        imageBytes = bytes.buffer.asUint8List();
      } else {
        imageBytes = (await NetworkAssetBundle(Uri.parse(imageUrl)).load(imageUrl)).buffer.asUint8List();
      }

      final result = await ImageGallerySaver.saveImage(imageBytes);
      if (result == null || result == '') {
        throw "图片保存失败";
      }
      return true;
    } catch (e) {
      return false;
    }
  }
}
